<?php

namespace app\index\model;

use think\Model;
use think\Session;
use app\common\traits\model\TraitModel;
use \app\common\traits\model\UserOperateCheck;

class Users extends Model
{
    use TraitModel,UserOperateCheck;
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    protected $table = 'users';
    //protected static $loginuser = '';
    /**
     * 获取登录用户信息
     * @param  string $field [description]
     * @return [type]        [description]
     */
    public static function getLoginUserInfo($field = '')
    {
        if (empty(self::$loginuser)) {
            self::$loginuser = self::getUserInfo(['id' => session('user.id')]);
        }
        if ($field) {
            if (isset(self::$loginuser[$field])) {
                return self::$loginuser[$field]; 
            }
            return false;
        }
        return self::$loginuser;
    }
    /**
     * 判断是否已经登陆
     * @return [type] [description]
     */
    public function checkLogin()
    {
        if ($user_token = cookie('token')) {
             if ($login_user = self::getUserInfo(['id' => $user_token])) {
                if (false == Session::has('user')) {
                    $this->setUserSession($login_user, true);
                }
            }
        }
        if (Session::has('user')) {
            $login_session_id = self::getLoginUserInfo('login_session_id');
            if ($login_session_id !== Session::get('user.login_session_id')){
                self::$loginuser = '';
                $this->logout();
                return false;
            }
        }
        return Session::has('user') ? true : false;    
    }
     /**
     * [getUserInfo description]
     * @param  array  $where [description]
     * @param  string $field [description]
     * @return [type]        [description]
     */
    public static function getUserInfo($where = [], $field = '')
    {
        if (empty($where)) {
            return false;
        }
        if ($userInfo = self::get($where)) {
            if ($field) {
                if (isset($userInfo->$field)) {
                    return $userInfo->$field; 
                }
                return false;
            }
            return $userInfo;
        }
        return false;        
        
    }

    /**
     * 退出登录
     * @return [type] [description]
     */
    public function logout()
    {
        $this->clearUserSession();
        cookie('token', null);
        return true;
    }

    /**
     * 清除用户session信息
     * @return [type] [description]
     */
    private function clearUserSession()
    {
        Session::delete('user');
    }

}
